<template>
	<view class="container">
		<form @submit="btnPay" :report-submit="true">
			<tui-list-cell :hover="false" :lineLeft="false">
				<view v-if="storeDetail.title" class="pay-title">
					{{storeDetail.title}}
				</view>
			</tui-list-cell>
			<tui-list-cell :hover="false" :lineLeft="false">
				<view class="tui-cell-input">
					<input name="amount" :placeholder="'消费金额,请询问服务员后输入'" placeholder-class="tui-phcolor" type="text"
						:auto-focus="true" :focus="true" maxlength="40" />
				</view>
			</tui-list-cell>
			
			<view style="border: 1rpx solid #FFEB3B;margin: 20rpx 30rpx;width: 90%;height: 51rpx;line-height: 51rpx;padding: 0 20rpx 0 20rpx;border-radius:20rpx;">				
				<text style="float: left;">积分：{{userInfoJifen}}</text>
				<radio style="transform:scale(0.7);float: right;" @click="userInfoJifenRadio" :checked="userInfoJifenRadioStr == 1"  />
				<view style="clear: both;"></view>
			</view>
				
			
			
			<view v-if="agreement.status==1" class="agreement" style="margin-left:30rpx;">
				<radio style="transform:scale(0.7)" @click="setagreementagree" :checked="agreementagree == 1" />
				<label @click="showagreementAlert">已阅并同意购买协议</label>
				<tui-modal :show="showagreement" @cancel="showagreement=false" padding="40rpx 40rpx" custom>
					<view class="tui-modal-agreement">
						<scroll-view :style="'height:'+(height-160)+'px'" scroll-y="true">
							<view class="tui-modal-agreement-text">
								<text>{{agreement.content}}</text>
							</view>
						</scroll-view>
						<tui-button height="72rpx" :size="28" type="danger" shape="circle"
							@click="hideagreementAlert">同意</tui-button>
					</view>
				</tui-modal>
			</view>
			
			<t-pay-way :show="payshow" :stylecolor="pagestyleconfig.appstylecolor"
				:amuont="setyouhuijine(setPayPoints(allGoodsAndYunPrice2)) || ''" @goPay="goPay" :paymethod="paymethod"
				@close="popupClose" :userInfoJifen="userInfoJifen" ></t-pay-way>
			
			<view class="tui-btn-box">
				<tui-button formType="submit" :shadow="false" height="88rpx" shape="circle" type="danger">确认支付
				</tui-button>
			</view>
		</form>
	</view>
</template>

<script>
	import pay from '@/common/pay.js'
	import tPayWay from "@/components/views/t-pay-way/t-pay-way"
	import tSelectCoupons from "@/components/views/t-select-coupons/t-select-coupons"
	import tSelectGoodsgiftcard from "@/components/views/t-select-goodsgiftcard/t-select-goodsgiftcard"
	
	export default {
		components: {
			tPayWay,
			tSelectCoupons,
			tSelectGoodsgiftcard
		},
		data() {
			return {
				sid: '',
				tid: '',
				tzid: '',
				storeDetail: {},
				agreementagree: 0,
				agreement: {},
				agreementagree: 0,
				showagreement: false,
				payshow: false,
				pagestyleconfig: [],
				allGoodsAndYunPrice: 0,
				paymethod: [],
				TuanzhangaddrData: [],
				ptype: 1,
				is_PayPoints: 0,
				totalPointsPrice: 0,
				coupon_type: 0, //优惠券类型
				userInfoJifen:0, // 个人积分额度
				userInfoJifenRadioStr:0,
				allGoodsAndYunPrice2:0
			};
		},
		onLoad: function(e) {
			const _this = this;
			if (e && e.scene) {
				const scene = decodeURIComponent(e.scene) // 处理扫码进商品详情页面的逻辑
				if (scene) {
					e.sid = scene.split(',')[0]
					if (scene.split(',')[1]) {
						e.tid = scene.split(',')[1];
					}
					if (scene.split(',')[2]) {
						e.tzid = scene.split(',')[2];
					}
				}
			}
			_this.$request.get('member.detail').then(res => {
				if(res.errno == 0){
					this.userInfoJifen = res.data.points;
				}
				
			})

			_this.$util.getUserInfo(function(userInfo) {
			});
			
			_this.$request.post('Agreement.index', {
				code: 'userstobuy'
			}).then(res => {
				if (res.errno == 0) {
					_this.agreement = res.data;
				}
			});

			if (e.sid) {
				_this.sid = e.sid;

				_this.$request.get('store.detail', {
					id: _this.sid
				}).then(res => {
					if (res.errno == 0) {
						_this.storeDetail = res.data
					}
				});

			}
			if (e.tid) {
				_this.tid = e.tid;
			}
			if (e.tzid) {
				_this.tzid = e.tzid;
			}
			
			_this.$request.get('Paymethod.list').then(res => {
				if (res.errno == 0) {
					_this.paymethod = res.data;
					_this.paymentType = res.data[0].default;
					//console.log(_this.paymentType);
				}
			});
			
			_this.$request.post('config', {
				mo: 'pagestyle'
			}).then(res => {
				if (res.errno == 0) {
					_this.pagestyleconfig = res.data
				}
			});
			
		},
		onShow: function() {

		},
		methods: {
			userInfoJifenRadio(){
				this.userInfoJifenRadioStr = 1				
			},
			goPay(e) {
				if (e.paymentType) {
					this.paymentType = e.paymentType;
				}
				this.createOrder();
			},
			popupClose() {
				this.payshow = false
			},
			setyouhuijine: function(amount) {
				// if (this.coupon_type == 10) {
				// 	var tmpamount = (amount - this.youhuijine).toFixed(2);
				// 	if(tmpamount>0){
				// 		return tmpamount;
				// 	}else{
				// 		return 0
				// 	}
					
				// } else {
				// 	if (this.coupon_type == 20 && this.discount) {
				// 		return ((amount * this.discount) / 10).toFixed(2);
				// 	}
				// }
				console.log(amount);
			
				return amount;
			},
			setagreementagree() {
				this.agreementagree = 1;
			},
			setPayPoints: function(amount) {
				// if (this.is_PayPoints == 1) {
				// 	return (amount - this.totalPointsPrice).toFixed(2);
				// } else {
					return amount;
				// }
			},
			getAuthMsg() {
			// 	return new Promise(resolve => {
			// 		if (this.tmplIds.length > 0) {
			// 			uni.requestSubscribeMessage({
			// 				tmplIds: this.tmplIds,			
			// 				fail(res) {
			// 					console.log(res);
			// 				},			
			// 				complete() {
			// 					resolve();
			// 				}			
			// 			});
			
			// 		} else {
			// 			resolve();
			// 		}
			// 	});
			},
			// async bindSave(e) {
			// 	const _this = this
			// 	const amount = e.detail.value.amount;
			// 	if (amount == "" || amount * 1 < 0) {
			// 		wx.showToast({
			// 			title: '请填写正确的付款金额',
			// 			icon: 'none'
			// 		})
			// 		return
			// 	}
			// 	const userMoney = await _this.$request.get('member.detail');
			// 	if (userMoney.errno != 0) {
			// 		wx.showToast({
			// 			title: userMoney.message,
			// 			icon: 'none'
			// 		})
			// 		return
			// 	}
			// 	let _msg = '您本次消费 ' + amount + ' 元'
			// 	let needPayAmount = amount * 1

			// 	if (userMoney.data.balance * 1 > 0) {
			// 		_msg += ',当前账户可用余额 ' + userMoney.data.balance + ' 元'
			// 	}
			// 	needPayAmount = needPayAmount.toFixed(2) // 需要买单支付的金额
			// 	const wxpayAmount = (needPayAmount - userMoney.data.balance).toFixed(2) // 需要额外微信支付的金额
				

			// 	if (wxpayAmount > 0) {
			// 		_msg += ',仍需微信支付 ' + wxpayAmount + ' 元'
			// 	}
				
			// 	const redirectUrl = "/pagesA/my/maidan/success";
			// 	wx.showModal({
			// 		title: '请确认消费金额',
			// 		content: _msg,
			// 		confirmText: "确认支付",
			// 		cancelText: "取消支付",
			// 		success: function(res) {
						
			// 			if (res.confirm) {

			// 				_this.$request.post('order.paybillcreate', {
			// 					amount: amount,
			// 					sid: _this.sid,
			// 					tid: _this.tid,
			// 					tzid: _this.tzid,
			// 				}).then(res => {
			// 					if (res.errno == 0) {
			// 						if (res.data.wxpayAmount > 0) {
			// 							pay.wxpay('paybill-' + res.data.order_num_alias,
			// 								res.data.wxpayAmount, 0, redirectUrl);
			// 						} else {
			// 							wx.showModal({
			// 								title: '成功',
			// 								content: '买单成功，欢迎下次光临！',
			// 								showCancel: false,
			// 								success: function(res) {
			// 									wx.redirectTo({
			// 										url: redirectUrl
			// 									});
			// 								}
			// 							})
			// 						}

			// 					} else {
			// 						wx.showModal({
			// 							title: '失败',
			// 							content: res.msg,
			// 							showCancel: false
			// 						})
			// 					}
			// 				})



			// 			}
			// 		}
			// 	});
			// },
			
			btnPay(e) {
				const amount = e.detail.value.amount;
				console.log(amount);
				if(amount <= 0){
					this.tui.toast("请输入金额");
					return;
				}
				
				if (this.agreementagree != 1 && this.agreement.status == 1) {
					this.tui.toast("请仔细阅读并勾选购买协议");
					return;
				}
				this.allGoodsAndYunPrice = amount;
				this.allGoodsAndYunPrice2 = amount;
				
				if(this.userInfoJifenRadioStr == 1){
					if(this.userInfoJifen*1 >= amount*1){
						this.allGoodsAndYunPrice2 = '0';
					}else{
						this.allGoodsAndYunPrice2 = amount - this.userInfoJifen
					}					
				}
				
				// #ifdef MP-WEIXIN
				this.getAuthMsg()
				//#endif
				// if (this.amount == 0) {
				// 	this.createOrder();
				// } else if (this.setyouhuijine(this.setPayPoints(this.amount)) == 0) {
				// 	this.createOrder();
				// } else if (this.curGoodsgiftcard) {
				// 	if (this.curGoodsgiftcard.id) {
				// 		this.createOrder();
				// 	} else {
				// 		this.payshow = true
				// 	}
				// } else {
					this.payshow = true
				// }
			},
			createOrder: function() {
				var _this = this;
			
				if (_this.remark == undefined) {
					_this.remark = '';
				}
				let postData = {
					technicalId: _this.technicalId,
					sid: _this.sid,
					cartid: _this.cartid,
					remark: _this.remark,
					paymentType: _this.paymentType,
					orderimage: _this.orderimage
				};
				if (_this.buyNowgoods != undefined) {
					if (_this.buyNowgoods.goods_id) {
						postData.goodsId = _this.buyNowgoods.goods_id;
					}
					if (_this.buyNowgoods.combination_ids) {
						postData.combination_ids = _this.buyNowgoods.combination_ids;
					}
					if (_this.buyNowgoods.msid) {
						postData.msid = _this.buyNowgoods.msid;
					}
					if (_this.buyNowgoods.tuanid) {
						postData.tuanid = _this.buyNowgoods.tuanid;
					}
					if (_this.buyNowgoods.jointuanid) {
						postData.jointuanid = _this.buyNowgoods.jointuanid;
					}
			
					if (_this.buyNowgoods.sku) {
						postData.sku = _this.buyNowgoods.sku;
					}
					if (_this.buyNowgoods.number) {
						postData.number = _this.buyNowgoods.number;
					}
					if (_this.buyNowgoods.is_skumore) {
						postData.is_skumore = _this.buyNowgoods.is_skumore;
					}
					if (_this.buyNowgoods.skumore) {
						postData.skumore = JSON.stringify(_this.buyNowgoods.skumore);
					}
				}
			
				if (_this.kjId) {
					postData.kjid = _this.kjId
				}
				if (_this.paymentType == 0) {
					uni.hideLoading();
					uni.showModal({
						title: '错误',
						content: '请选择支付方式！',
						showCancel: false
					})
					return;
				}
				postData.payment = postData.paymentType;
				postData.is_times = _this.is_times;
			
				// if (_this.deliverymode == 1 || _this.deliverymode == 2 || _this.deliverymode == 4) {
				// 	if (_this.is_times == 0 && _this.ptype == 2) {
				// 		if (!_this.servicetime) {
				// 			uni.hideLoading();
				// 			uni.showModal({
				// 				title: '错误',
				// 				content: '请选择预约时间！',
				// 				showCancel: false
				// 			})
				// 			return;
				// 		}
				// 		postData.servicetime = _this.servicetime;
				// 	}
				// }
			
			// 	if (_this.deliverymode == 1 || _this.deliverymode == 3) {
			// 		if (!_this.curAddressData.address_default) {
			// 			uni.hideLoading();
			// 			uni.showModal({
			// 				title: '错误',
			// 				content: '请先设置您的地址！',
			// 				showCancel: false
			// 			})
			// 			return;
			// 		}
			// 		postData.shipping = '1';
			// 		postData.address_id = _this.curAddressData.id;
			// 	}
			
				// if (_this.deliverymode == 2) {
				// 	if (!_this.storeaddrData.id) {
				// 		uni.hideLoading();
				// 		uni.showModal({
				// 			title: '错误',
				// 			content: '请选择门店！',
				// 			showCancel: false
				// 		})
				// 		return;
				// 	}
				// 	if (!_this.sid) {
				// 		postData.sid = _this.storeaddrData.id;
				// 	}
				// }
			
				// if (_this.deliverymode == 5) {
				// 	if (!_this.TuanzhangaddrData.id) {
				// 		uni.hideLoading();
				// 		uni.showModal({
				// 			title: '错误',
				// 			content: '请选择自提点！',
				// 			showCancel: false
				// 		})
				// 		return;
				// 	}			
				// }
				
				// postData.tz_id = _this.TuanzhangaddrData.id;
				// if (_this.curCoupon) {
				// 	postData.couponId = _this.curCoupon.id;
				// }
				// if (_this.curGoodsgiftcard) {
				// 	postData.goodsgiftcardId = _this.curGoodsgiftcard.id;
				// }
			
				postData.is_PayPoints = _this.is_PayPoints;
				postData.deliverymode = _this.deliverymode;
				postData.total = _this.allGoodsAndYunPrice
				postData.ptype = 4;
				postData.is_points = this.userInfoJifenRadioStr;
				
				// 提交支付结果
				_this.$request.post('order.create', postData).then(res => {
					if (res.errno != 0) {
						uni.showModal({
							title: '错误',
							content: res.msg,
							showCancel: false
						})
						return;
					}
			
					// if ("buyNow" != _this.orderType) {
					// 	// 清空购物车数据
					// 	uni.removeStorageSync('shopCarInfo');
					// }
					const orderid = res.data.id;			
					const redirectUrl = "/pagesA/my/maidan/success";
					
					if (res.data.payment_code == 'wx_pay') {
						console.log(res.data);
						pay.wxpay('order', res.data.pay_total, res.data.id, redirectUrl);
					} else if (res.data.payment_code == 'ali_pay') {
						console.log(res.data);
						pay.alipay('order', res.data.pay_total, res.data.id, redirectUrl);
					} else if (res.data.payment_code == 'balance_pay') {
						_this.$request.post('order.pay', {
							orderid: orderid
						}).then(res => {
							if (res.errno == 0) {
								wx.showModal({
									title: '成功',
									content: '使用余额支付成功',
									showCancel: false,
									success: function(res) {
										wx.redirectTo({
											url: redirectUrl
										});
									}
								})
			// 					_this.$request.post('message.payorder', {
			// 						orderid: orderid
			// 					}).then(res => {
			
			// 					})
			
							} else {
								wx.showModal({
									title: '失败',
									content: res.msg,
									showCancel: false
								})
							}
						})
					} else if (res.data.payment_code == 'goodsgiftcard_pay') {
			// 			_this.$request.post('order.goodsgiftcardpay', {
			// 				orderid: orderid
			// 			}).then(res => {
			// 				if (res.errno == 0) {
			// 					wx.showModal({
			// 						title: '成功',
			// 						content: '使用购物卡抵扣成功',
			// 						showCancel: false,
			// 						success: function(res) {
			// 							wx.redirectTo({
			// 								url: redirectUrl
			// 							});
			// 						}
			// 					})
			// 					_this.$request.post('message.payorder', {
			// 						orderid: orderid
			// 					}).then(res => {
			
			// 					})
			
			// 				} else {
			// 					wx.showModal({
			// 						title: '失败',
			// 						content: res.msg,
			// 						showCancel: false
			// 					})
			// 				}
			// 			})
					} else if (res.data.payment_code == 'offline_pay') {
			// 			_this.sam.navigateTo('/pagesA/submitOrder/offlinepayment?id=' + res.data.id);
					} else if (res.data.payment_code == 'delivery_pay') {
			// 			_this.sam.navigateTo(redirectUrl);
					} else {
						wx.showModal({
							title: '支付失败',
							content: res.msg,
							showCancel: false
						})
					}
			
				})
			}
		},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 200);
		},
	};
</script>

<style lang="scss">
	.container {
		padding-top: 20rpx;

		.pay-title {
			font-size: 36rpx;
			width: 100%;
			text-align: center;
			align-items: center;
			box-sizing: border-box;
		}

		.tui-cell-input {
			width: 100%;
			display: flex;
			align-items: center;
			box-sizing: border-box;

			input {
				flex: 1;
				padding-left: $uni-spacing-row-base;
			}
		}

		.tui-btn-box {
			padding: 40rpx 30rpx 10rpx 30rpx;
			box-sizing: border-box;
		}
	}
</style>